<?php
namespace app\houtai\controller;

class IndexController extends BaseController {
  /**
   *  @brief  : 后台框架页面
   *  @return : page
   *  @details: 
   */
  public function indexAction() {
    $Admin = table('Ky_Admin a', 'rydb.websms')->field([
      'a.AdminId', 'a.UserName', 'a.NickName', 'a.IsSys', 'a.IsDisabled',
      'a.IsDelete', 'a.RoleID', "ISNULL(b.Title, '')" => 'RoleName',
    ])
    ->join('Ky_AdminRole b', 'b.ID = a.RoleID', 'LEFT')
    ->where(['a.AdminId' => $this->auid])
    ->find();

    return $this->fetch('', ['Admin' => $Admin]);
  }
  /**
   *  @brief  : 管理中心页片
   *  @return : page
   *  @details: 
   */
  public function homeAction() {
    return $this->fetch();
  }
  /**
   *  @brief : session清除并注销
   *  @return:
   *  @detail:
   */
  public function logoutAction() {
    session(null);
    $this->redirect(config('auth.getway'));
  }

    /**
     * 清除缓存
     */
  public function clearaAction() {
        if (delete_dir_file(CACHE_PATH) || delete_dir_file(TEMP_PATH)) {
            return result([], 1, '清除成功');
        } else {
            return result([], 101, '清除失败');
        }
  }
  /**
   *  @brief  : 修改密码页面&&请求
   *  @return : page
   *  @details: 
   */
  public function uppwdAction() {
    if ($this->request->isGet()) {
      $user = table('Ky_Admin a', 'rydb.websms')->where(['AdminId' => $this->auid])->find();
      return $this->fetch('', ['user' => $user]);
    }
    if ($this->request->isPost()) { // 修改保存
      //--- 验证器验证 ---
      $data = $this->request->only(['UserName', 'PassWord', 'NickName', 'Email', 'Mobile', 'IsDisabled']);
      $retn = $this->validate($data, [ // 按照顺序逐一判断
        // '__token__'           => 'require|token',
        'UserName|登陆账号'   => 'min:1|max:20|regex:/^[\S]+$/',
        'PassWord|登陆密码'   => 'max:50|regex:/^[\S]+$/',
        'NickName|用户昵称'   => 'require|length:1,20|chsDash',
        'Email|邮箱'          => 'email',
        'Mobile|手机'         => 'mobile',
        'IsDisabled|是否禁用' => 'accepted',
      ]);
      if (true !== $retn) {
        return $this->error($retn);
      }
      //--- 数据库验证 ---
      if (!empty($data['PassWord'])) {
        $data['PassWord'] = password_hash($data['PassWord'], PASSWORD_BCRYPT); // 计算新密码
      } else {
        unset($data['PassWord']); // 为空不修改
      }
      
      $data['IsDisabled'] = empty($data['IsDisabled']) ? 0 : 1;
      $eax = table('Ky_Admin', 'rydb.websms')->where('AdminId', $this->auid)->update($data);
      if ($eax) {
        session(null);
        $url = config('auth.getway');
        $this->success('更新成功', $url); // 修改当前用户需重新登陆
      } else {
        $this->success('更新失败');
      }
    }
  }
}
